#This R code replicates the results in Toni, Paniagua and Órdenes 2024
#Policy Changes and Growth Slowdown: Assessing the Lost Decade of the Latin American Miracle

rm(list = ls())
options(scipen = 999)

# Loading  necessary libraries
library(Synth)
library(dplyr)
library(writexl)

# Loading panel data
data <- read.csv("data_WB_constant_2015.csv",sep=";") # BENCHMARK RESULTS CONSTANT 2015 USD
#data <- read.csv("data_WB_constant_PPP.csv",sep=";") # constant PPP. 
#data <- read.csv("data_WB_current_USD.csv",sep=";") #  current USD
data$country_name <- as.character(data$country_name)
data$country_code <- as.character(data$country_code)

# Set the treated unit (country) index for which you want to estimate the treatment effect
treated_country <- 'Chile'  # Replace this with the index of the country you want to treat

# Identify the pre-treatment and post-treatment periods (intervention year 2014)
pre_treatment_period <- c(1990, 2013)   
post_treatment_period <- c(2013, 2019)  

# Create the outcome and covariates matrices
outcome <- data[data$country_name == treated_country, "gdp"]

covariate_names <- c(names(data)[4:12]) #all [4:12]

covariate_names

data <- data %>%
  mutate_at(c(all_of(covariate_names)), ~as.numeric(gsub(",", ".", .)))

covariates <- data %>% subset(country_name != treated_country) %>% select(all_of(covariate_names))

data$country_index = as.numeric(factor(data$country_name))


# Synthetic_Estimation ----------------------------------------------
data.out.at11 <-				
  dataprep(data,				
           predictors = covariate_names,				
           dependent     = "gdp",				
           unit.variable = "country_index",	
           time.variable = "year",				
           unit.names.variable = "country_name",
           treatment.identifier  = 6,
           controls.identifier   = c(1:5,7:23),	
           time.predictors.prior = c(1990:2013),				
           time.optimize.ssr     = c(1990:2013), #intervention set to 2014
           time.plot             = c(1990:2019))			

#All Countries (GROUP 2) = c(1:5,7:23)
#GROUP 1 = c(1,3,4,8:13,15:17,23) LATIN NEIGHBOURS

synth.out.at11 <- synth(data.out.at11)	

synth.tables.at11   <- synth.tab(				
  dataprep.res = data.out.at11,				
  synth.res    = synth.out.at11)	

synth.tables.at11

# Coutnry Weights ----------------
w.at11 <- as.data.frame(synth.tables.at11$tab.w)				
w.at11	

# # Save results excel
# file_path <- "/Users/emilianotoni/Desktop/Synth_Faro_CODES/R_CODES/all_countries_weights.xlsx"
# # Use the write_xlsx function to save the data frame to an Excel file
# write_xlsx(w.at11, path = file_path)
# # Print a message to confirm the file has been saved
# cat("Data has been saved to", file_path, "\n")

w_suficiente <- w.at11 %>% subset(w.weights > 0.001)
w_suficiente

# # Save results excel
 #file_path <- "/Users/emilianotoni/Desktop/Synth_Faro_CODES/R_CODES/weights_country_constantUSD.xlsx"
# # Use the write_xlsx function to save the data frame to an Excel file
# write_xlsx(w_suficiente, path = file_path)
# # Print a message to confirm the file has been saved
# cat("Data has been saved to", file_path, "\n")


# Variables weights ----------------
v.at11 <- as.data.frame(synth.tables.at11$tab.v)				
v.at11				

v_suficiente <- v.at11 %>% subset(v.weights > 0.001)
v_suficiente

# # Save results excel
# file_path <- "/Users/emilianotoni/Desktop/Synth_Faro_CODES/R_CODES/weights_variables.xlsx"
# # Use the write_xlsx function to save the data frame to an Excel file
# write_xlsx(v.at11, path = file_path)
# # Print a message to confirm the file has been saved
# cat("Data has been saved to", file_path, "\n")


#-----Matching treated vs Synth--------
matching <- as.data.frame(synth.tables.at11$tab.pred)	
matching

# # Save results excel
#file_path <- "/Users/emilianotoni/Desktop/Synth_Faro_CODES/R_CODES/results_group2.xlsx"
# # Use the write_xlsx function to save the data frame to an Excel file
#write_xlsx(matching, path = file_path)
# # Print a message to confirm the file has been saved
#cat("Data has been saved to", file_path, "\n")


# Creating plot to visualize results --------
path.plot(
  dataprep.res = data.out.at11, # los datos preparados
  synth.res = synth.out.at11,       # los resultados de la función synth()
  Main = "Chile's GDP Per Capita",    # el título principal del gráfico
  Ylab = "GDP per capita",         # la etiqueta del eje y
  Xlab = "Year",                    # la etiqueta del eje x
  Legend = c("Chile", "Synthetic Chile"), # la leyenda
  # CI = TRUE                        # si quieres incluir un intervalo de confianza
)


# Vertical line on intervention year (color rojo)
abline(v = 2014, col = "red")


# Generating vector with values for synthetic Chile--------------------------------

data_synth_chile <- data.out.at11$Y0plot%*%synth.out.at11$solution.w

data_synth_chile <- cbind.data.frame(country_name = 'Synthetic Chile',
                                     year = row.names(data_synth_chile),
                                     gdp = data_synth_chile)

data_synth_chile <- data_synth_chile %>% rename(gdp = w.weight)
data_synth_chile


## Specify the file path where you want to save the Excel file
#file_path <- "/Users/emilianotoni/Desktop/Synth_Faro_CODES/R_CODES/results_group2.xlsx"
## Use the write_xlsx function to save the data frame to an Excel file
#write_xlsx(data_synth_chile, path = file_path)
## Print a message to confirm the file has been saved
#cat("Data has been saved to", file_path, "\n")

### GUIDE TO GENERATE PAPER RESULTS --------------------------

#To generate results in Table 2 just use the weights estimated and saved in line 66-75...
#... remember to change set of countries for group 1 and 2. See line 55-56.

#To generate results in Table 3 just use results estimated in line 103-112.

#To generate results in Figure 5, just run this code normally up to line 128. See 
#... Excel "Main_Replication_results" sheet "Group2_results". 

#To generate results in Figure 6, we just take result in figure 5 and apply an HP...
#...filter directly in Excel, result available in Excel "Main_Replication_results" sheet "Group2_HP".  

#Results in figure 7 are the same in fig.5, but with an extra GDP projection...
#... in which case result is done in Excel "Main_Replication_results" sheet "Ext_Int_simul.".

#To generate results in Fig.8, just change the year to 2005...
#...(because the intervention year is 2006) in lines 23-24;51-52 (where the benchmark is 2013)

#To generate results in Fig.9, just change the country index that you want to treat...
#... in this case 1 by 1 for all 23 countries, save results and then plot them...
#... you can find this in Excel "Main_Replication_results" sheet "Country_placebo2". 


#Results in Table 4 come as a residual from previous procedure. 

#Results in Figure 10 are estimated in MATLAB. See file p_values.m.  

#To generate results in Fig.11, just drop one by one the main donor countries (China,...
#... Costa Rica, Australia, Uruguay, Panama) and repeat the initial procedure. Keep in...
#... mind footnote 15.


#To generate results in appendix just change the initial data base in lines 13-15 where...
#... you can choose GDP at current, constant and PPP USD. Results are displayed in...
#... Excel "Main_Replication_results"






